<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<a-tabs v-model:activeKey="activeKey" @change="onTableTypeChange">
			<a-tab-pane :key="0" tab="我的客户"></a-tab-pane>
			<a-tab-pane :key="1" tab="协作客户"></a-tab-pane>
		</a-tabs>

		<div class="flex items-center flex-wrap">
			<a-input-group compact class="w-[300px] mr-[12px] mb-[12px]">
				<a-select v-model:value="searchType" style="width: 100px" @change="searchTypeChange">
					<a-select-option :value="0">客户名称</a-select-option>
					<a-select-option :value="5">客户编号</a-select-option>
					<a-select-option :value="4">内部编号</a-select-option>
					<a-select-option :value="1">联系方式</a-select-option>
					<a-select-option :value="2">跟进人</a-select-option>
					<a-select-option :value="3">前跟进人</a-select-option>
				</a-select>
				<a-input
					v-model:value="searchTextComputed"
					style="width: 200px"
					placeholder="请输入关键字搜索"
					allowClear
					@pressEnter="table.clearRefreshSelected(true)"
				></a-input>
			</a-input-group>
			<template v-if="!activeKey">
				<a-select
					placeholder="请选择查询范围"
					v-model:value="searchForm.data"
					allowClear
					class="w-[200px] mr-[12px] mb-[12px]"
					@change="dataChange"
				>
					<a-select-option v-if="store.roleAuthMap.self" value="1">本人</a-select-option>
					<a-select-option v-if="store.roleAuthMap.dept" value="2">本部门</a-select-option>
					<a-select-option v-if="store.roleAuthMap.deptAndSub" value="3">本部门及下级部门</a-select-option>
					<a-select-option v-if="store.roleAuthMap.all" value="4">全企业</a-select-option>
					<a-select-option v-if="store.roleAuthMap.dept" value="5" @click="onCustomClick">自定义</a-select-option>
				</a-select>
				<a-tree-select
					v-if="searchForm.data === '5'"
					v-model:value="searchForm.tempPersonIds"
					style="width: 360px"
					class="mr-[12px] mb-[12px]"
					:tree-data="orgUserTreeData"
					tree-checkable
					allow-clear
					:show-checked-strategy="SHOW_PARENT"
					placeholder="请选择人员范围"
					tree-node-filter-prop="label"
					:fieldNames="fieldNames"
					max-tag-count="responsive"
					:dropdownMatchSelectWidth="false"
					treeNodeFilterProp="name"
					@change="onPersonChange"
				/>
			</template>
			<a-select
				v-model:value="searchForm.customerLevelId"
				placeholder="请选择等级"
				allowClear
				:options="levelOptions"
				class="w-[170px] mr-[12px] mb-[12px]"
			></a-select>
			<div class="w-[170px] mr-[12px] mb-[12px]">
				<select-tag-popover v-model:value="searchForm.labelList" :type="2" />
			</div>
			<a-button type="primary" class="mr-[12px] mb-[12px]" @click="table.clearRefreshSelected(true)">查询</a-button>
			<div class="flex-1 flex justify-between items-center mr-[12px] mb-[12px]">
				<a-button @click="screenVisible = true">更多筛选</a-button>
				<a-button v-if="hasPerm('bizPurposeAdd') && !activeKey" type="primary" @click="newCustomerVisible = true"
					>新增客户</a-button
				>
			</div>
		</div>
	</a-card>
	<!--	class="h-full"-->
	<a-card>
		<a-space v-if="hasPerm('bizPurposeBatchRecycle') && !activeKey" :size="16" class="mb-6">
			<div>批量操作</div>
			<a-button type="primary" @click="toBatch">批量回收</a-button>
		</a-space>
		<s-table
			ref="table"
			:columns="
				!activeKey
					? [
							...columns,
							{
								title: '操作',
								dataIndex: 'action',
								align: 'center',
								fixed: 'right',
								width: '150px'
							}
					  ]
					: columns
			"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="
				!activeKey
					? {
							selectedRowKeys: selectedContacts,
							onChange: onSelectChange,
							getCheckboxProps: getCheckboxProps
					  }
					: null
			"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'customerRef'">
					<div class="flex justify-center items-center">
						<template v-if="record.customerRef">
							<span>{{ record.customerRef }}</span>
							<el-icon class="ml-1 cursor-pointer" color="rgb(16, 142, 233)" @click="onCopyCustomerRef(record)">
								<el-icon-CopyDocument />
							</el-icon>
						</template>
						<span v-else>-</span>
					</div>
				</template>
				<template v-if="column.dataIndex === 'customerName'">
					<a-space>
						<div class="truncate w-[280px]" :title="record.customerName">
							<el-popover v-if="record.customerBeans.length" placement="top" width="auto" trigger="hover">
								<template #reference>
									<a v-if="hasPerm('bizPurposeView')" @click="onDetail(record)"> {{ record.customerName }}</a>
									<span v-else>{{ record.customerName }}</span>
								</template>

								<div class="max-h-[200px] overflow-y-auto scrollbar-thumb">
									<div v-for="(item, index) in record.customerBeans" :key="index" class="my-1">
										<el-text class="mx-1 cursor-pointer" type="primary" @click="onRouteToDetail(item)">{{
											item.customerName
										}}</el-text>
									</div>
								</div>
							</el-popover>
							<template v-else>
								<a v-if="hasPerm('bizPurposeView')" @click="onDetail(record)"> {{ record.customerName }}</a>
								<span v-else>{{ record.customerName }}</span>
							</template>
						</div>
						<a-tag v-if="record.customerType === 1" color="#108ee9">企业</a-tag>
						<a-tag v-if="record.customerType === 2" color="#108ee9">自然人</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'followUpStatus'">
					<span>{{ followUpMap[record.followUpStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'contactPerson'">
					<a-popover trigger="click" placement="left">
						<template #content>
							<a-spin :spinning="spinning">
								<div ref="scollBox" class="max-h-[280px] overflow-y-auto p-3" @scroll="scollMore">
									<div v-for="item in showPersons" :key="item.id" class="flex justify-between my-1">
										<div class="mr-2">{{ item.contactsName || '---' }}</div>
										<div>
											手机：
											<a
												@click="
													callPhone(
														item.id,
														record.customerCode,
														item.contactsPhone,
														record.customerName,
														record.followUpStatus,
														record
													)
												"
											>
												<PhoneFilled style="transform: rotateY(180deg)" />{{ item.contactsPhone }}
											</a>
										</div>
									</div>
									<div class="text-center">
										<a-spin :spinning="loadingSpinning" size="small" class="mb-[10px]" />
									</div>
								</div>
							</a-spin>
						</template>
						<a @click.stop="getPersons(record.customerCode)">
							<PhoneFilled style="transform: rotateY(180deg)" />
							{{ record.nummber }}条
						</a>
					</a-popover>
				</template>
				<template v-if="column.dataIndex === 'labelNames'">
					<tag-list-space v-if="record.labelNames" :list="record.labelNames?.split(',')" :show-num="2" />
					<span v-else>-</span>
				</template>
				<template v-if="column.dataIndex === 'receiveWay'">
					<span>{{ customerRecordEnum[record.receiveWay] }}</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a
							v-if="!activeKey && hasPerm('bizPurposeRecycle') && record.followUpStatus !== 2"
							@click="singleRecovery(record.id)"
							>回收公海</a
						>
						<a v-if="hasPerm('bizPurposeView')" @click="addContract(record)">新增合同</a>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal v-model:visible="screenVisible" title="更多筛选" :footer="null" :closable="false" :width="500">
		<a-form :label-col="{ style: { width: '100px' } }">
			<a-form-item label="客户类型">
				<a-select v-model:value="moreSearch.customerType" allowClear>
					<a-select-option :value="1">企业</a-select-option>
					<a-select-option :value="2">自然人</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="客户来源">
				<a-select v-model:value="moreSearch.customerFromId" :options="customerFromOptions" allowClear></a-select>
			</a-form-item>
			<a-form-item label="录入方式">
				<a-select v-model:value="moreSearch.receiveWay" :options="customerRecord" allowClear></a-select>
			</a-form-item>
			<a-form-item label="转介绍数量">
				<a-input-group compact>
					<a-select style="width: 30%" v-model:value="moreSearch.operators" placeholder="请选择">
						<a-select-option value="gt">></a-select-option>
						<a-select-option value="eq">=</a-select-option>
						<a-select-option value="lt">&lt;</a-select-option>
					</a-select>
					<a-input-number style="width: 70%" v-model:value="moreSearch.introNum" placeholder="请输入" />
				</a-input-group>
			</a-form-item>
			<a-form-item label="跟进状态">
				<a-select v-model:value="moreSearch.followUpStatus" allowClear>
					<a-select-option v-for="item in followUpOptions" :key="item.value" :value="item.value">{{
						item.label
					}}</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="所属行业">
				<industry-select ref="industrySelectRef" :value="moreSearch.industryId" />
			</a-form-item>
			<a-form-item label="所属地区">
				<area-select ref="areaSelectRef" :value="moreSearch.districtId" />
			</a-form-item>
			<a-form-item label="呼叫状态">
				<a-select v-model:value="moreSearch.callState" :options="callStatusOptions" allowClear></a-select>
			</a-form-item>
			<a-form-item v-if="!activeKey" label="协作人">
				<a-tree-select
					v-model:value="moreSearch.concertId"
					:tree-data="store.selectableDeptList"
					allow-clear
					show-search
					tree-node-filter-prop="label"
					:fieldNames="fieldNames"
					max-tag-count="responsive"
					:dropdownMatchSelectWidth="false"
					treeNodeFilterProp="name"
				/>
			</a-form-item>
			<a-form-item label="意向产品">
				<a-cascader
					v-model:value="moreSearch.serviceIds"
					:options="categoryOptions"
					:show-search="{ filter: categoryFilter }"
				/>
			</a-form-item>
			<a-form-item label="创建客户时间">
				<a-range-picker valueFormat="YYYY-MM-DD" v-model:value="timeSearch.createAt" allowClear style="width: 100%" />
			</a-form-item>
			<a-form-item label="最近跟进时间">
				<a-range-picker
					valueFormat="YYYY-MM-DD"
					v-model:value="timeSearch.followUpTime"
					allowClear
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="掉保时间">
				<a-range-picker valueFormat="YYYY-MM-DD" v-model:value="timeSearch.dropTime" allowClear style="width: 100%" />
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="clearFilter">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="filter">筛选</a-button>
				<a-button @click="screenVisible = false">取消</a-button>
			</a-space>
		</div>
	</a-modal>
	<!-- 自定义选择部门 -->
	<a-modal v-model:visible="selfChooseVisible" title="自定义选择部门" @ok="selfSearch">
		<div class="max-h-[400px] overflow-auto">
			<a-tree
				v-if="treeData.length > 0"
				v-model:selectedKeys="treeKeys"
				v-model:expandedKeys="defaultExpandedKeys"
				:tree-data="treeData"
				:field-names="treeFieldNames"
				@select="treeSelect"
			>
			</a-tree>
		</div>
	</a-modal>
	<!-- 新增客户 -->
	<customer-modal
		v-if="newCustomerVisible"
		type="new"
		:callBack="customerApi.addCustomer"
		v-model:visible="newCustomerVisible"
		@finished="table.refresh(true)"
	/>
	<!-- 回收公海 -->
	<recovery-modal
		v-if="recoveryVisible"
		v-model:visible="recoveryVisible"
		:list="selectedContacts"
		@finished="table.refresh(true)"
		@cancel="cancelRecovery"
	/>
	<!-- 新增合同 -->
	<add-contract-modal
		v-model:visible="addContractVisible"
		:info="contractInfo"
		:from="1"
		@finished="table.refresh(true)"
	/>
</template>
<script setup>
	import customerModal from './customerModal.vue'
	import customerApi from '@/api/biz/customerApi'
	import customerLevelApi from '@/api/biz/crm/customerLevelApi'
	import customerSourceApi from '@/api/biz/crm/customerSourceApi'
	import orgApi from '@/api/biz/bizOrgApi'
	import recoveryModal from './recoveryModal.vue'
	import areaSelect from './areaSelect.vue'
	import industrySelect from './industrySelect.vue'
	import { message, TreeSelect } from 'ant-design-vue'
	import { isEmpty } from 'lodash-es'
	import {
		customerRecord,
		customerRecordEnum,
		callStatusOptions,
		followUpOptions,
		followUpMap
	} from '@/views/biz/contractManagement/enum/contractEnum'
	import tool from '@/utils/tool'
	import { globalStore } from '@/store'
	import erpProjectApi from '@/api/erp/erpProjectApi'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'
	import useTableFilter from '@/hook/useTableFilter'
	import AddContractModal from '@/views/biz/contractManagement/addContractModal.vue'
	import { ElMessage } from 'element-plus'

	const router = useRouter()
	const tableCache = useTableCache('customerManagement', ['customerManagement', 'customerDetail'])
	const tableFilter = useTableFilter('customerManagementFilter', 'customerDetail')

	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			searchType.value = tableCacheData.searchType
			searchText.value = tableCacheData.searchText
			searchForm.value = tableCacheData.searchForm
			timeSearch.value = tableCacheData.timeSearch
			moreSearch.value = tableCacheData.moreSearch
			activeKey.value = tableCacheData.activeKey
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}
	})

	const store = globalStore()

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	const searchType = ref(0)
	const searchText = ref('')
	const searchTextComputed = computed({
		get() {
			return searchText.value
		},
		set(val) {
			searchText.value = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const columns = [
		{
			title: '客户编号',
			dataIndex: 'customerRef',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '客户名称',
			dataIndex: 'customerName',
			width: 360,
			align: 'center',
			ellipsis: true
		},
		{
			title: '客户来源',
			dataIndex: 'customerFrom',
			width: 200,
			align: 'center',
			ellipsis: true
		},
		{
			title: '内部编号',
			dataIndex: 'insideCode',
			width: 240,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '联系方式',
			dataIndex: 'contactPerson',
			width: 200,
			align: 'center',
			ellipsis: true
		},
		{
			title: '标签',
			dataIndex: 'labelNames',
			width: 320,
			align: 'center',
			ellipsis: true
		},
		{
			title: '客户等级',
			dataIndex: 'customerLevelName',
			align: 'center',
			width: 120
		},
		{
			title: '创建客户时间',
			dataIndex: 'createAt',
			width: 150,
			align: 'center'
		},
		{
			title: '最近跟进时间',
			dataIndex: 'followUpTime',
			width: 150,
			align: 'center'
		},
		{
			title: '掉保时间',
			dataIndex: 'dropTime',
			width: 150,
			align: 'center'
		},
		{
			title: '录入方式',
			dataIndex: 'receiveWay',
			width: 120,
			align: 'center'
		},
		{
			title: '跟进状态',
			dataIndex: 'followUpStatus',
			width: 200,
			ellipsis: true,
			align: 'center'
		},
		{
			title: '跟进人',
			dataIndex: 'followUpPerson',
			width: 100,
			align: 'center'
		},
		// {
		// 	title: '前跟进人',
		// 	dataIndex: 'followUpBefperson',
		// 	width: 150,
		// 	align: 'center'
		// }
		{
			title: '协作人',
			dataIndex: 'concertName',
			width: 160,
			align: 'center',
			ellipsis: true
		},
		{
			title: '客户意向产品',
			dataIndex: 'serviceProjectName',
			width: 160,
			align: 'center',
			ellipsis: true
		},
		{
			title: '预估成交金额',
			dataIndex: 'predictAmount',
			width: 150,
			align: 'center'
		}
	]
	// columns.push({
	// 	title: '操作',
	// 	dataIndex: 'action',
	// 	align: 'center',
	// 	fixed: 'right',
	// 	width: '150px'
	// })
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)
	const pageNum = ref(1)
	const pageSize = ref(10)

	const searchForm = ref({
		customerName: '',
		insideCode: '',
		contactPhone: '',
		followUpBefperson: '',
		followUpPerson: '',
		data: undefined,
		datastr: undefined,
		customerLevelId: undefined,
		tempPersonIds: [],
		personIds: [],
		labelList: []
	})
	const searchTypeChange = () => {
		searchText.value = ''
		searchForm.value.customerName = ''
		searchForm.value.customerRef = ''
		searchForm.value.insideCode = ''
		searchForm.value.contactPhone = ''
		searchForm.value.followUpBefperson = ''
		searchForm.value.followUpPerson = ''
	}

	/**
	 * ====================
	 *     自定义部门逻辑
	 * ====================
	 */
	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref(store.authDeptList)
	const onPersonChange = (value, label, extra) => {
		searchForm.value.personIds = tool.getAllBottomPersonIds(extra.allCheckedNodes)
	}

	const selfChooseVisible = ref(false)
	const dataChange = (value) => {
		// if (searchForm.value.data === '5') {
		// 	orgApi.orgTree().then((res) => {
		// 		if (res !== null) {
		// 			treeData.value = res
		// 			if (isEmpty(defaultExpandedKeys.value)) {
		// 				// 默认展开2级
		// 				treeData.value.forEach((item) => {
		// 					// 因为0的顶级
		// 					if (item.parentId === '0') {
		// 						defaultExpandedKeys.value.push(item.id)
		// 						// 取到下级ID
		// 						if (item.children) {
		// 							item.children.forEach((items) => {
		// 								defaultExpandedKeys.value.push(items.id)
		// 							})
		// 						}
		// 					}
		// 				})
		// 			}
		// 		}
		// 		selfChooseVisible.value = true
		// 	})
		// }

		nextTick(() => {
			if (value !== '5') {
				onCustomClick()
			}
		})
	}
	const onCustomClick = () => {
		searchForm.value.tempPersonIds = []
		searchForm.value.personIds = []
	}

	const treeData = ref([])
	const defaultExpandedKeys = ref([])
	const treeKeys = ref([])
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const treeSelect = (value) => {
		searchForm.value.datastr = value[0]
	}
	const selfSearch = () => {
		table.value.clearRefreshSelected(true)
		selfChooseVisible.value = false
	}
	/**
	 * 获取客户列表数据
	 */
	const areaSelectRef = ref(null)
	const industrySelectRef = ref(null)
	const loadData = (parameter) => {
		switch (searchType.value) {
			case 0:
				searchForm.value.customerName = searchText.value
				break
			case 1:
				searchForm.value.contactPhone = searchText.value
				break
			case 2:
				searchForm.value.followUpPerson = searchText.value
				break
			case 3:
				searchForm.value.followUpBefperson = searchText.value
				break
			case 4:
				searchForm.value.insideCode = searchText.value
				break
			case 5:
				searchForm.value.customerRef = searchText.value
				break
		}
		const { tempPersonIds, personIds, labelList, ...other } = searchForm.value
		const { concertId, serviceIds, ...otherParams } = moreSearch.value
		let serviceClassId = '',
			serviceTypeId = '',
			serviceProjectId = ''
		if (serviceIds && serviceIds.length) {
			serviceClassId = serviceIds[0]
			serviceTypeId = serviceIds[1]
			serviceProjectId = serviceIds[2]
		}

		const params = {
			...other,
			...parameter,
			...otherParams,
			dataStr: personIds.join(','),
			type: activeKey.value,
			concertId: concertId ? concertId.substr(2) : '',
			serviceClassId,
			serviceTypeId,
			serviceProjectId,
			labelList: labelList && labelList.length ? labelList.join(',') : null
		}
		tableFilter.set(params)
		return customerApi.getCustomerList(params).then((res) => {
			return res
		})
	}

	const activeKey = ref(0)
	const onTableTypeChange = (value) => {
		Object.assign(searchForm.value, {
			customerName: '',
			insideCode: '',
			contactPhone: '',
			followUpBefperson: '',
			followUpPerson: '',
			data: undefined,
			datastr: undefined,
			customerLevelId: undefined,
			tempPersonIds: [],
			personIds: []
		})
		moreSearch.value = { ...moreDefaultSearch }
		table.value.clearRefreshSelected(true)
	}

	/**
	 * 点击联系人条数获取联系人列表
	 */
	const spinning = ref(false)
	const loadingSpinning = ref(false)
	const showPersons = ref([])
	const personSize = ref(30)
	const getPersonCode = ref('')
	const personTotal = ref(0)
	const getPersons = (code) => {
		if (code) {
			showPersons.value = []
			spinning.value = true
		} else {
			loadingSpinning.value = true
		}

		const getSize = code ? 30 : personSize.value
		const params = {
			customerCode: code ?? getPersonCode.value,
			current: 1,
			size: getSize
		}
		customerApi
			.getPersonList(params)
			.then((res) => {
				spinning.value = false
				loadingSpinning.value = false
				showPersons.value = res.records
				personTotal.value = res.total
				if (code) {
					getPersonCode.value = code
				}
			})
			.catch(() => {
				spinning.value = false
				loadingSpinning.value = false
			})
	}
	const scollBox = ref(null)
	const scollMore = () => {
		if (showPersons.value.length >= personTotal.value) {
			return
		}
		const onBottom = Math.ceil(scollBox.value.scrollTop + scollBox.value.offsetHeight) >= scollBox.value.scrollHeight
		if (onBottom) {
			personSize.value += 10
			getPersons()
		}
	}
	/**
	 * 更多筛选
	 */
	const screenVisible = ref(false)
	const moreDefaultSearch = {
		customerType: '',
		customerFromId: '',
		followUpStatus: '',
		industryId: '',
		districtId: '',
		callState: '',
		receiveWay: '',
		concertId: '',
		serviceIds: [],
		operators: null,
		introNum: null
	}
	const timeSearch = ref({
		createAt: [],
		followUpTime: [],
		dropTime: []
	})
	const moreSearch = ref({ ...moreDefaultSearch })

	/**
	 * 获取客户来源选项
	 */
	const customerFromOptions = ref([])
	customerSourceApi.list().then((res) => {
		customerFromOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
	})
	/**
	 * 获取客户等级选项
	 */
	const levelOptions = ref([])
	customerLevelApi.list().then((res) => {
		levelOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
	})

	/**
	 * 意向产品
	 */
	const categoryOptions = ref([])
	erpProjectApi.serviceProjectTree().then((res) => {
		categoryOptions.value = res
	})
	const categoryFilter = (inputValue, path) => {
		return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
	}

	/**
	 * 筛选
	 */
	const filter = () => {
		const { createAt, followUpTime, dropTime } = timeSearch.value
		moreSearch.value.SCreateAt = createAt ? createAt[0] : null
		moreSearch.value.SFollowUpTime = followUpTime ? followUpTime[0] : null
		moreSearch.value.SDropTime = dropTime ? dropTime[0] : null
		moreSearch.value.ECreateAt = createAt ? createAt[1] : null
		moreSearch.value.EFollowUpTime = followUpTime ? followUpTime[1] : null
		moreSearch.value.EDropTime = dropTime ? dropTime[1] : null
		const { select: industrySelect } = industrySelectRef.value
		moreSearch.value.industryId = industrySelect ? String(industrySelect) : null
		const { select: areaSelect } = areaSelectRef.value
		moreSearch.value.districtId = areaSelect && areaSelect.length ? areaSelect.join(',') : null
		screenVisible.value = false
		table.value.clearRefreshSelected(true)
	}

	const clearFilter = () => {
		moreSearch.value = { ...moreDefaultSearch }
		timeSearch.value.createAt = []
		timeSearch.value.followUpTime = []
		timeSearch.value.dropTime = []
		industrySelectRef.value.select = ''
		areaSelectRef.value.select = []
	}

	/**
	 * 拨号
	 * @param {*} code customercode
	 * @param {*} id 联系人记录id
	 * @param {*} phone 手机号
	 * @param {*} name 名称
	 * @param {*} status 状态
	 * @param record
	 */
	const callPhone = (id, code, phone, name, status, record) => {
		store.dashboardNode?.open({ id, code, phone, name, type: 2, status })
		nextTick(() => {
			store.tagIdList = record.labelIds ? record.labelIds.split(',') : []
			store.tagNameList = record.labelNames ? record.labelNames.split(',') : []
		})
	}
	/**
	 * 新增客户
	 */
	const newCustomerVisible = ref(false)

	/**
	 * 复制客户编号
	 */
	const onCopyCustomerRef = ({ customerRef }) => {
		tool.copyText(customerRef).then(() =>
			ElMessage({
				message: '复制成功',
				type: 'success'
			})
		)
	}

	/**
	 * 详情
	 */
	const onDetail = ({ id, customerCode }) => {
		tool.limitClick(() => {
			const { localPagination } = table.value
			tableCache.set({
				searchType: searchType.value,
				searchText: searchText.value,
				searchForm: searchForm.value,
				timeSearch: timeSearch.value,
				moreSearch: moreSearch.value,
				activeKey: activeKey.value,
				pageNum: localPagination.current,
				pageSize: localPagination.pageSize
			})
			router.push({
				path: `/biz/customerManagement/customerDetail/${id}`,
				query: { type: activeKey.value }
			})
		})
	}

	/**
	 * 跳转关联客户详情
	 */
	const onRouteToDetail = (item) => {
		switch (item.type) {
			// type 2-客户私海 3-客户公海 4-线索私海 5-线索公海
			// belongTo - 0-我的客户 1-协作客户
			case 2:
				router.push({
					path: `/biz/customerManagement/customerDetail/${item.id}`,
					query: { type: item.belongTo }
				})
				break
			case 3:
				router.push(`/biz/highSeas/detail?id=${item.id}`)
				break
			case 4:
				break
			case 5:
				break
		}
	}

	/**
	 * 回收公海
	 */
	const selectedContacts = ref([])
	const onSelectChange = (selectedRowKeys) => {
		selectedContacts.value = []
		selectedContacts.value = selectedRowKeys
	}
	const recoveryVisible = ref(false)
	const getCheckboxProps = (record) => {
		return { disabled: record.followUpStatus === 2 }
	}
	// 列表操作单个回收
	const singleRecovery = (id) => {
		selectedContacts.value = []
		table.value.updateSelect([])
		table.value.updateSelect([id])
		selectedContacts.value.push(id)
		recoveryVisible.value = true
	}
	// 批量回收
	const toBatch = () => {
		if (selectedContacts.value.length === 0) {
			message.warning('请选择客户')
			return
		}
		recoveryVisible.value = true
	}
	// 取消回收
	const cancelRecovery = () => {
		table.value.updateSelect([])
		selectedContacts.value = []
	}

	// 新增合同
	const addContractVisible = ref(false)
	const contractInfo = ref(null)
	const addContract = (record) => {
		contractInfo.value = {
			signMethod: '0',
			signPayment: 'OnlineSignedPaid',
			paymentMethod: 'FULL',
			templateId: '',
			templateName: '',
			serviceCategory: '',
			serviceCategoryId: '',
			signType: '1',
			secondPartyName: '',
			secondPartyPerson: '',
			secondPartyAddress: '',
			secondPartyMobile: '',
			secondPartyId: '',
			list: [],
			balancePaymentTime: '',
			contractImg: '',
			voucherImg: '',
			remark: '',
			// 甲方信息
			customerRef: record.customerRef,
			customerCode: record.customerCode,
			customerType: record.customerType,
			firstParty: record.customerName,
			firstPartyAddress: record.customerAddress,
			firstPartyMobile: record.contactPhone,
			firstPartyPerson: record.contactPerson
		}
		addContractVisible.value = true
	}
</script>
<style lang="less" scoped>
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 420px);
	// }
</style>
